<?php
/**
 * Created by PhpStorm.
 * User: Jiawei
 * Date: 2017/7/29
 * Time: 17:39
 */

namespace App\Lib\WeApp\Api;


use App\Models\User\WxUser;
use App\Wen\Utils\Settings;
use Illuminate\Support\Facades\Cache;

class BaseApi
{
	protected $appid;
	protected $secret;
	protected $platform;

	public function __construct($appid,$secret, $platform)
	{
		$this->appid = $appid;
		$this->secret = $secret;
		$this->platform = $platform;
	}

	public function getAccessToken($force_update = false){
	    if(!$force_update){
            $token = Cache::get($this->appid.'_'.$this->platform.'_token', '');
            if($token){
                return $token;
            }
        }


		$url = ApiUrl::ACCESS_TOKEN;
        $param = array(
            'grant_type'  => 'client_credential',
            'appid'  => $this->appid,
            'secret'  => $this->secret,
        );

		$res = $this->sendHttpRequest($url,$param,null,false);
		if(!isset($res['access_token'])){
			throw new WeAppException($res['errcode'].':'.$res['errmsg'],$res['errcode']);
		}

		Cache::put($this->appid.'_'.$this->platform.'_token', $res['access_token'], $res['expires_in']-200);
		return $res['access_token'];
	}

	public function sendRequestWithToken($url,$body_param = null,$is_post = true){
		$token = array(
			'access_token'  =>  $this->getAccessToken()
		);
		return $this->sendHttpRequest($url,$token,$body_param,$is_post);
	}

	/**
	 * @param string $url
	 * @param array $url_param
	 * @param array $body_param
	 * @param bool $is_post
	 * @return mixed
	 * @throws WeAppException
	 */
	public function sendHttpRequest($url,$url_param = null,$body_param = null,$is_post = true){

		if($url_param){
		    if(!$is_post){
		        if($body_param){
		            if(_empty_($url_param)){
                        $url_param = [];
                    }
                    $url_param = array_merge($url_param, $body_param);
                }
            }
			$url_param = '?'.http_build_query($url_param);
		}


        if($body_param){
            $body_param = json_encode($body_param,JSON_UNESCAPED_UNICODE);
        }

		$ch = curl_init($url.$url_param);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		if($is_post){
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $body_param);
		}
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		$data = curl_exec($ch);
		curl_close($ch);
		$array_data = json_decode($data,true);
		if($array_data){
			if( isset($array_data['errcode']) && $array_data['errcode']!=0 ){
                if($array_data['errcode'] == 43004){
                    if($this->platform == 'mini'){

                    }else if($this->platform == 'mp'){
                        $body_param_arr = json_decode($body_param, true);
                        if($body_param_arr && _array_key($body_param_arr, 'touser', '')){
                            $user_id = WxUser::where('weixin_mp_openid', _array_key($body_param_arr, 'touser', ''))->value('id');
                            if($user_id && $user_id > 0){
                                update_user_meta($user_id, 'is_follow_mp', 0, 'n');
                            }
                        }
//                        _logger_(__file__, __line__, '该用户取消关注了你的公众号，推送失败'.$body_param);
                    }

                    return null;
                }else if($array_data['errcode'] == 40001 && !Cache::has('weapp:sendHttpRequest')){
                    $token = array(
                        'access_token'  =>  $this->getAccessToken(true)
                    );
                    Cache::put('weapp:sendHttpRequest', 1, 600);
                    return $this->sendHttpRequest($url,$token,$body_param,$is_post);
                }else{
                    if($array_data['errcode'] == '40125'){
                        if($this->platform == 'mini'){
                            _logger_(__file__, __line__, '小程序appsecret错误，请至 [全局配置-支付-微信-小程序] 进行配置');
                            throw new \Exception('小程序appsecret错误，请至 [全局配置-支付-微信-小程序] 进行配置');
                        }else if($this->platform == 'mp'){
                            _logger_(__file__, __line__, '公众号appsecret错误，请至 [全局配置-支付-微信-公众号] 进行配置');
                            throw new \Exception('公众号appsecret错误，请至 [全局配置-支付-微信-公众号] 进行配置');
                        }
                    }else{
                        throw new WeAppException($array_data['errcode'].':'.$array_data['errmsg'], $array_data['errcode']);
                    }
                }
			}
            if($this->platform == 'mp'){
                $body_param_arr = json_decode($body_param, true);
                if($body_param_arr && _array_key($body_param_arr, 'touser', '')){
                    $user_id = WxUser::where('weixin_mp_openid', _array_key($body_param_arr, 'touser', ''))->value('id');
                    if($user_id && $user_id > 0){
                        update_user_meta($user_id, 'is_follow_mp', 1, 'n');
                    }
                }
            }
			return $array_data;
		}

		return $data;
	}

}
